package com.dupt.system.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.dupt.common.utils.DateUtils;
import com.dupt.common.utils.SecurityUtils;
import com.dupt.system.domain.*;
import com.dupt.system.domain.vo.MaterialBillDetialVo;
import com.dupt.system.mapper.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dupt.system.service.IAssemblePlanService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 组装计划Service业务层处理
 * 
 * @author zhuanyu.sun
 * @date 2025-07-10
 */
@Service
public class AssemblePlanServiceImpl implements IAssemblePlanService
{
    @Autowired
    private AssemblePlanMapper assemblePlanMapper;
    @Autowired
    private MaterialBillDetialMapper materialBillDetialMapper;
    @Autowired
    private AssembleMaterialMapper assembleMaterialMapper;
    @Autowired
    private MaterialBillMainMapper materialBillMainMapper;
//    @Autowired
//    private MaterialCollectMapper materialCollectMapper;
    @Autowired
    private MaterialDetialMapper materialDetialMapper;
    @Autowired
    private MaterialSerialMapper materialSerialMapper;

    /**
     * 查询组装计划
     * 
     * @param assembleId 组装计划主键
     * @return 组装计划
     */
    @Override
    public AssemblePlan selectAssemblePlanByAssembleId(String assembleId)
    {
        return assemblePlanMapper.selectAssemblePlanByAssembleId(assembleId);
    }

    /**
     * 查询组装计划列表
     * 
     * @param assemblePlan 组装计划
     * @return 组装计划
     */
    @Override
    public List<AssemblePlan> selectAssemblePlanList(AssemblePlan assemblePlan)
    {
        return assemblePlanMapper.selectAssemblePlanList(assemblePlan);
    }

    /**
     * 新增组装计划
     * 
     * @param assemblePlan 组装计划
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAssemblePlan(AssemblePlan assemblePlan) {
        // 1. 初始化组装计划信息
        initAssemblePlan(assemblePlan);

        // 2. 获取BOM配件明细
        List<MaterialBillDetialVo> billDetialVoList = materialBillDetialMapper
                .selectMaterialBillDetialByMaterialBillMainId(assemblePlan.getMaterialBillMainId());

        //3.将BOM配件相关信息保存到组装物料表中
        List<AssembleMaterial> assembleMaterialList = new ArrayList<>();//组装物料
        billDetialVoList.forEach(detail -> {
            //3.1 创建组装物料记录
            AssembleMaterial assembleMaterial = new AssembleMaterial();
            assembleMaterial.setAssemblePlanId(assemblePlan.getAssembleId());
            assembleMaterial.setMaterialCollectId(detail.getMaterialCollectId());
            assembleMaterial.setAmount(detail.getCounts());
            assembleMaterial.setCreateBy(SecurityUtils.getLoginUser().getUsername());
            assembleMaterial.setCreateTime(DateUtils.getNowDate());
            assembleMaterialList.add(assembleMaterial);

            //3.2 自动分配相关物料
            //根据物料ID查询物料收集表
//            MaterialCollect materialCollect = materialCollectMapper.selectMaterialCollectByMaterialCollectId(detail.getMaterialCollectId());
            //根据内码查询物料明细表
//            List<MaterialDetial> detialList = materialDetialMapper.selectMaterialDetialByMaterialInnerCode(materialCollect.getMaterialInnerCode());
            //获取所有的明细ID
            //获取所有的序列号ID
//            List<String> materialDetialIds = detialList.stream()
//                    .map(MaterialDetial::getMaterialDetialId)
//                    .collect(Collectors.toList());
            //根据materialDetialId查询状态为1的所有序列号
//            List<MaterialSerial> serialList = materialSerialMapper.selectMaterialSerialByMaterialDetialIds(materialDetialIds);
            //修改序列号表相关信息
//            if (detail.getCounts() > serialList.size()) {
//                // 大于时：全部替换
//                for (MaterialSerial serial : serialList) {
//                    serial.setUsedId(detail.getMaterialBillDetialId());
//                    serial.setCurrentPos(assemblePlan.getAssembleBillNo());
//                    serial.setStatus("3");
//                    serial.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
//                    serial.setUpdateTime(DateUtils.getNowDate());
//                }
//                materialCollect.setUsedAmount(materialCollect.getUsedAmount() + serialList.size());
//                materialCollect.setAvailableAmount(materialCollect.getAvailableAmount() - serialList.size());
//            } else {
//                materialCollect.setUsedAmount(materialCollect.getUsedAmount() + detail.getCounts());
//                materialCollect.setAvailableAmount(materialCollect.getAvailableAmount() - detail.getCounts());
//                // 小于等于时：仅替换前N个
//                for (int i = 0; i < detail.getCounts(); i++) {
//                    serialList.get(i).setUsedId(detail.getMaterialBillDetialId());
//                    serialList.get(i).setStatus("3");
//                    serialList.get(i).setCurrentPos(assemblePlan.getAssembleBillNo());
//                    serialList.get(i).setUpdateBy(SecurityUtils.getLoginUser().getUsername());
//                    serialList.get(i).setUpdateTime(DateUtils.getNowDate());
//                }
//            }
            //3.3 修改物料采集表中相关的数量
//            materialCollect.setUsedAmount((materialCollect.getUsedAmount() + detail.getCounts())>materialCollect.getTotalAmount()?materialCollect.getTotalAmount():((materialCollect.getUsedAmount() + detail.getCounts())));
//            materialCollect.setAvailableAmount((materialCollect.getAvailableAmount() - detail.getCounts())<0?0:(materialCollect.getAvailableAmount() - detail.getCounts()));
//            //3.3更新序列号表信息
//            materialSerialMapper.batchUpdateMaterialSerial(serialList);
            //3.4 修改物料采集表信息
//            materialCollectMapper.updateMaterialCollect(materialCollect);
        });

        //4.保存或修改信息
        //4.1 保存组装计划信息
        assemblePlanMapper.insertAssemblePlan(assemblePlan);
        //4.2保存组装明细信息
        if(assembleMaterialList.size()>0){
            assembleMaterialMapper.batchInsertAssembleMaterial(assembleMaterialList);
        }
        return 1;
    }

    // 初始化组装计划
    private void initAssemblePlan(AssemblePlan plan) {
        // 生成组装计划编号（格式：ZZJH + 当前时间）
        plan.setAssembleBillNo("ZZJH" + DateUtils.dateTimeNow());
        // 生成唯一组装计划ID
        plan.setAssembleId(UUID.randomUUID().toString());
        // 设置创建时间
        plan.setCreateTime(DateUtils.getNowDate());
        // 设置创建人信息
        plan.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        plan.setPrincipal(SecurityUtils.getLoginUser().getUsername());
        plan.setPrincipalDingtalkId(SecurityUtils.getLoginUser().getDingtalkId());
        // 设置默认状态为未组装
        plan.setAssembleStatus("1"); // 1表示待处理
    }

    /**
     * 修改组装计划
     * 
     * @param assemblePlan 组装计划
     * @return 结果
     */
    @Override
    public int updateAssemblePlan(AssemblePlan assemblePlan)
    {
        assemblePlan.setUpdateTime(DateUtils.getNowDate());
        return assemblePlanMapper.updateAssemblePlan(assemblePlan);
    }

    /**
     * 批量删除组装计划
     * 
     * @param assembleIds 需要删除的组装计划主键
     * @return 结果
     */
    @Override
    public int deleteAssemblePlanByAssembleIds(String[] assembleIds)
    {
        return assemblePlanMapper.deleteAssemblePlanByAssembleIds(assembleIds);
    }

    /**
     * 删除组装计划信息
     * 
     * @param assembleId 组装计划主键
     * @return 结果
     */
    @Override
    public int deleteAssemblePlanByAssembleId(String assembleId)
    {
        return assemblePlanMapper.deleteAssemblePlanByAssembleId(assembleId);
    }

    /**
     * 组装计划入库
     *
     * @param assemblePlan 组装计划
     * @return 结果
     */
    @Override
    public int inStorage(AssemblePlan assemblePlan) {
        //根据ID查询相关信息
        AssemblePlan plan = assemblePlanMapper.selectAssemblePlanByAssembleId(assemblePlan.getAssembleId());
        if(plan!=null){
            //根据物料主表ID查询相关信息
            MaterialBillMain billMain = materialBillMainMapper.selectMaterialBillMainByMaterialBillMainId(plan.getMaterialBillMainId());
            if(billMain!=null){
//                MaterialMode mode = materialModeMapper.selectMaterialModeByMaterialModeId(billMain.getMaterialModeId());
//                if(mode!=null){
//                    ProductLibrary productLibrary = new ProductLibrary();
//                    productLibrary.setProductType(plan.getProductType());
//                    productLibrary.setProductInnerCode(mode.getMaterialInnerCode());
//                    productLibrary.setProductCode(mode.getMaterialCode());
//                    productLibrary.setProductName(mode.getMaterialName());
//                    productLibrary.setProductItem(mode.getMaterialItem());
//                    productLibrary.setProductSerialNo(mode.getManufactureNo());
//                    productLibrary.setProductNo(plan.getSeriesNo());
//                    productLibrary.setProductPrecision(mode.getMaterialPrecision());
//                    productLibrary.setProductDescribe(mode.getMaterialDescribe());
//                    productLibrary.setManufactureNo(mode.getManufactureNo());
//                    productLibrary.setManufacturer(mode.getManufacturer());
//                    productLibrary.setProductionTime(DateUtils.getNowDate());
//                    productLibrary.setApplicableTemp(mode.getApplicableTemp());
//                    productLibrary.setAmount(1L);
//                    productLibrary.setUnit(mode.getUnit());
//                    productLibrary.setBeforePos("科技研究院库");
//                    productLibrary.setCurrentPos("科技研究院库");
//                    productLibrary.setRemark(plan.getRemark());
//                    productLibrary.setCreateBy(SecurityUtils.getLoginUser().getUsername());
//                    productLibrary.setCreateTime(DateUtils.getNowDate());
//                    productLibraryMapper.insertProductLibrary(productLibrary);
//                }
            }
        }
        plan.setAssembleStatus("3");
        return assemblePlanMapper.updateAssemblePlan(plan);
    }

    @Override
    public List<AssemblePlan> planList() {
        return assemblePlanMapper.planList ();
    }
}
